package com.shebei.api.equipment_api_test.service;

import com.shebei.api.equipment_api_test.dao.ApiNameQueryDAO;
import com.shebei.api.equipment_api_test.dao.CaseExcuteResultDAO;
import com.shebei.api.equipment_api_test.dao.UserCaseWoDAO;
import com.shebei.api.equipment_api_test.http.HttpClienInterface;
import com.shebei.api.equipment_api_test.http.HttpClientFactory;
import com.shebei.api.equipment_api_test.model.ApiNameQuery;
import com.shebei.api.equipment_api_test.model.CaseExcuteResultWithBLOBs;
import com.shebei.api.equipment_api_test.model.UserCaseWoWithBLOBs;
import com.shebei.api.equipment_api_test.model.responseModel.ApiResModel;
import com.shebei.api.equipment_api_test.selenium.UtilSelenium;
import com.shebei.api.equipment_api_test.utils.GetConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class UserCaseExcute {


    @Autowired
  private   UserCaseWoDAO userCaseWoDAO;

    @Autowired
   private ApiNameQueryDAO apiNameQueryDAO;
    @Autowired
   private ParamParsing paramParsing;
    @Autowired
    private  HeadParsing headParsing;

    @Autowired
    private HttpClientFactory httpClientFactory;
    @Autowired
    private  CheckPathParsing checkPathParsing;
    @Autowired
    private  ParamSave paramSave;

    @Autowired
    private CaseExcuteResultDAO caseExcuteResultDAO;

    @Autowired
    UtilSelenium utilSelenium;
    public void excute(String userName){
       try {


        String env=getEnv();
        System.out.println("userName:"+userName);
           UserCaseWoWithBLOBs userCaseWo=userCaseWoDAO.selectByUserName(userName);
        String apiName=userCaseWo.getApiName();
        String checkPath=userCaseWo.getCheckPath();
        String requestBody=userCaseWo.getRequestBody();
        String scene=userCaseWo.getScene();
        String saveParam=userCaseWo.getParameterSavePath();
        String catgoryModule=userCaseWo.getModule();
        System.out.println("开始执行用例："+userName +"  模块："+catgoryModule + " 环境为："+env);
        ApiNameQuery apiNameQuery= apiNameQueryDAO.selectByName(apiName);
        String path=apiNameQuery.getApiValue();
        String contentType=apiNameQuery.getApiType();
        String  requestType=apiNameQuery.getRequestType();
        String headInfo=apiNameQuery.getHeadInfo();

        String pathValue=paramParsing.parsingValue(path,scene,catgoryModule,env);  //解析请求path路径中的变量
           String url=pathValue;
           String apiGroup=apiNameQuery.getApiGroup();
           if(apiNameQuery.getApiGroup()==null ||(apiNameQuery.getApiGroup()!=null&&!apiNameQuery.getApiGroup().equals("url"))){
               url = paramParsing.getURL(scene, catgoryModule, pathValue, env);
           }

        String bodyValue=paramParsing.parsingValue(requestBody,scene,catgoryModule,env); //解析body请求中的变量。


        HttpClienInterface httpClient=httpClientFactory.getHttpClient(requestType,contentType); //获取HTTP接口请求


        Map head =headParsing.getHead(headInfo,scene,catgoryModule,env); //获取请求头信息

        isNull( httpClient, userName ); //判断是否得到http请求
        String response=httpClient.sendRequest(url,bodyValue,head);  //发送请求
        System.out.println("response:"+response);
        Map<String,String> errorResult= new ConcurrentHashMap<>();

        String compareResult= checkPathParsing.checkResponse(checkPath,response,errorResult,scene,catgoryModule,env); //检查点比对 并记录比对结果到errorResult

        paramSave.save( response, saveParam, scene, catgoryModule, compareResult,env); //关联参数存储；
        ResultAssertion.assertCleanResult( userCaseWo, compareResult,  errorResult); //断言 产生html结果
       } catch (Exception e){
           System.out.println("userName:"+userName);
       }
    }

    public String excuteSigleOne(Integer id){
        UserCaseWoWithBLOBs userCaseWo=   userCaseWoDAO.selectByPrimaryKey(id);
        String env="test";
       String userName=userCaseWo.getUserCaseName();
        String apiName=userCaseWo.getApiName();
        String checkPath=userCaseWo.getCheckPath();
        String requestBody=userCaseWo.getRequestBody();
        String scene=userCaseWo.getScene();
        String saveParam=userCaseWo.getParameterSavePath();
        String catgoryModule=userCaseWo.getModule();
        Integer iterSequece=userCaseWo.getExcuteSequence();
        if(iterSequece==null){
            return "请填写执行顺序，不写会导致用例回归没有顺序而报错";
        }
        System.out.println("开始执行用例："+userName +"  模块："+catgoryModule + " 环境为："+env);
        ApiNameQuery apiNameQuery= apiNameQueryDAO.selectByName(apiName);
        String path=apiNameQuery.getApiValue();
        String contentType=apiNameQuery.getApiType();
        String  requestType=apiNameQuery.getRequestType();
        String headInfo=apiNameQuery.getHeadInfo();

        String pathValue=paramParsing.parsingValue(path,scene,catgoryModule,env);  //解析请求path路径中的变量
        String url=pathValue;
        if(apiNameQuery.getApiGroup()==null ||(apiNameQuery.getApiGroup()!=null&&!apiNameQuery.getApiGroup().equals("url"))){
            url = paramParsing.getURL(scene, catgoryModule, pathValue, env);
        }

        String bodyValue=paramParsing.parsingValue(requestBody,scene,catgoryModule,env); //解析body请求中的变量。


        HttpClienInterface httpClient=httpClientFactory.getHttpClient(requestType,contentType); //获取HTTP接口请求


        Map head =headParsing.getHead(headInfo,scene,catgoryModule,env); //获取请求头信息

        isNull( httpClient, userName ); //判断是否得到http请求
        String response=httpClient.sendRequest(url,bodyValue,head);  //发送请求
        System.out.println("response:"+response);
        Map<String,String> errorResult= new ConcurrentHashMap<>();

        String compareResult= checkPathParsing.checkResponse(checkPath,response,errorResult,scene,catgoryModule,env); //检查点比对 并记录比对结果到errorResult

        paramSave.save( response, saveParam, scene, catgoryModule, compareResult,env); //关联参数存储；
        return response;
    }

//执行一个用例
    public ApiResModel vueExcuteOneCase(Integer id, String env){

        ApiResModel apiResModel=new ApiResModel();

        UserCaseWoWithBLOBs userCaseWo = userCaseWoDAO.selectByPrimaryKey(id);
            String userName = userCaseWo.getUserCaseName();
            String apiName = userCaseWo.getApiName();
            String checkPath = userCaseWo.getCheckPath();
            String requestBody = userCaseWo.getRequestBody();
            String scene = userCaseWo.getScene();
            String saveParam = userCaseWo.getParameterSavePath();
            String catgoryModule = userCaseWo.getModule();
            System.out.println("开始执行用例：" + userName + "  模块：" + catgoryModule + " 环境为：" + env);
        try {
            ApiNameQuery apiNameQuery = apiNameQueryDAO.selectByName(apiName);
            String path = apiNameQuery.getApiValue();
            String contentType = apiNameQuery.getApiType();
            String requestType = apiNameQuery.getRequestType();
            String headInfo = apiNameQuery.getHeadInfo();

            String pathValue = paramParsing.parsingValue(path, scene, catgoryModule, env);  //解析请求path路径中的变量
            String url=pathValue;
            if(apiNameQuery.getApiGroup()==null ||(apiNameQuery.getApiGroup()!=null&&!apiNameQuery.getApiGroup().equals("url"))){
                url = paramParsing.getURL(scene, catgoryModule, pathValue, env);
            }



            String bodyValue = paramParsing.parsingValue(requestBody, scene, catgoryModule, env); //解析body请求中的变量。


            HttpClienInterface httpClient = httpClientFactory.getHttpClient(requestType, contentType); //获取HTTP接口请求


            Map head = headParsing.getHead(headInfo, scene, catgoryModule, env); //获取请求头信息

            isNull(httpClient, userName); //判断是否得到http请求
            String response = httpClient.sendRequest(url, bodyValue, head);  //发送请求
            System.out.println("response:" + response);
            Map<String, String> errorResult = new ConcurrentHashMap<>();

            String compareResult = checkPathParsing.checkResponse(checkPath, response, errorResult, scene, catgoryModule, env); //检查点比对 并记录比对结果到errorResult

            paramSave.save(response, saveParam, scene, catgoryModule, compareResult, env); //关联参数存储；

            apiResModel.setUrl(url);
            apiResModel.setResponse(response);
            apiResModel.setRequestBody(bodyValue);
            apiResModel.setExcuteResult(compareResult);
            apiResModel.setErrMsg(errorResult.toString());
            return apiResModel;
        }catch (Exception e){
            String errMsg=userName +" 用例执行异常"+"参数保存为非json格式或者body体为非json格式";
            apiResModel.setResponse(errMsg);
            return apiResModel;
        }

    }


    public void vueSceneExcute(UserCaseWoWithBLOBs userCaseWo, String env, CaseExcuteResultWithBLOBs caseExcuteResultWithBLOBs){

        String apiName = userCaseWo.getApiName();
        String checkPath = userCaseWo.getCheckPath();
        String requestBody = userCaseWo.getRequestBody();
        String scene = userCaseWo.getScene();
        String saveParam = userCaseWo.getParameterSavePath();
        String catgoryModule = userCaseWo.getModule();
        String userName=userCaseWo.getUserCaseName();

        System.out.println("开始执行用例：" + userName + "  模块：" + catgoryModule + " 环境为：" + env);
        try {
            ApiNameQuery apiNameQuery = apiNameQueryDAO.selectByName(apiName);
            String path = apiNameQuery.getApiValue();
            String contentType = apiNameQuery.getApiType();
            String requestType = apiNameQuery.getRequestType();
            String headInfo = apiNameQuery.getHeadInfo();

            String pathValue = paramParsing.parsingValue(path, scene, catgoryModule, env);  //解析请求path路径中的变量
            String url=pathValue;
            if(apiNameQuery.getApiGroup()==null ||(apiNameQuery.getApiGroup()!=null&&!apiNameQuery.getApiGroup().equals("url"))){
                url = paramParsing.getURL(scene, catgoryModule, pathValue, env);
            }

            String bodyValue = paramParsing.parsingValue(requestBody, scene, catgoryModule, env); //解析body请求中的变量。


            HttpClienInterface httpClient = httpClientFactory.getHttpClient(requestType, contentType); //获取HTTP接口请求


            Map head = headParsing.getHead(headInfo, scene, catgoryModule, env); //获取请求头信息

            isNull(httpClient, userName); //判断是否得到http请求
            String response = httpClient.sendRequest(url, bodyValue, head);  //发送请求
            System.out.println("response:" + response);
            Map<String, String> errorResult = new ConcurrentHashMap<>();

            String compareResult = checkPathParsing.checkResponse(checkPath, response, errorResult, scene, catgoryModule, env); //检查点比对 并记录比对结果到errorResult

            paramSave.save(response, saveParam, scene, catgoryModule, compareResult, env); //关联参数存储；

            caseExcuteResultWithBLOBs.setRequestBody(bodyValue);
            caseExcuteResultWithBLOBs.setApiVaule(pathValue);
            caseExcuteResultWithBLOBs.setApiName(apiName);
            caseExcuteResultWithBLOBs.setErrorMsg(errorResult.toString());
            caseExcuteResultWithBLOBs.setResponseResult(response);
            caseExcuteResultWithBLOBs.setExcuteResult(compareResult);
            caseExcuteResultDAO.updateByPrimaryKeyWithBLOBs(caseExcuteResultWithBLOBs);


        }catch (Exception e){
            caseExcuteResultWithBLOBs.setExcuteResult("false");
            String errMsg=userName +"用例执行异常";
            caseExcuteResultWithBLOBs.setErrorMsg(errMsg);
            caseExcuteResultDAO.updateByPrimaryKeyWithBLOBs(caseExcuteResultWithBLOBs);

        }
    }

    private  void isNull(HttpClienInterface httpClient,String userName ){

        if (httpClient ==null){
            ResultAssertion.assertNull(userName);
        }

    }


    private String getEnv(){
        return GetConfig.getAddress("env").trim();
    }

}
